<?php
/**
 * Parse a Twitter Timeline Feed and add items into database.
 *
 * @package    urCronPlugin
 * @subpackage urCronServiceTwitterTimelinePlugin
 * @author     Marc Weistroff <marc.weistroff@gmail.com>
 * @version    $Id: urCronServiceTwitterUserTimeline.class.php 5 2009-06-09 09:15:55Z flambeur $
 */
class urCronServiceTwitterUserTimeline extends urCronServiceBase
{
  static function getServiceName()
  {
    return array('Twitter user Timeline', 'urCronServiceTwitterUserTimeline');
  }
  
  protected function doCronJobRss()
  {
    $nickname = $this->getNickname();

    foreach($this->feed->channel->item as $status)
    {
      if(Doctrine::getTable('urCronItem')->findOneByOriginalId((string)$status->guid))
        return;

      $this->object = new urCronItem();
      $tweet = str_replace($nickname.': ', '', (string)$status->title);
      $content = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '<a href="$1">$1</a>', $tweet);
      $isPublished = $tweet[0] == '@' ? false : sfConfig::get('app_urcron_autopublish', true);
      $publishedDate = date("Y-m-d H:i:s", strtotime((string)$status->pubDate));

      $data = array('original_id'             => (string)$status->guid,
                    'original_title'          => (string)$status->title,
                    'original_content'        => (string)$status->description,
                    'ur_cron_feed_id'         => $this->feedId,
                    'original_published_date' => $publishedDate,
                    'original_link'           => (string)$status->link,
                    'original_author'         => $nickname,
                    'is_published'            => $isPublished
                   );

      $this->object->synchronizeWithArray($data);
      $this->cleanItem();
      $this->object->save();
    }
  }

  /**
   * 
   */
  protected function cleanItem( )
  {
    $offset = strlen($this->getNickname().':');
    $title = substr($this->object->getOriginalTitle(), $offset);
    $content = $title;

    $this->object->setTitle($title);
    $this->object->setContent($content);

    $dispatcher = sfContext::getInstance()->getEventDispatcher();
    $dispatcher->notify(new sfEvent($this, 'urcron.post_clean.twitter_user_timeline'));
  }

  protected function getNickname()
  {
    return str_replace('Twitter / ', '', (string)$this->feed->channel->title);
  }
}